#! /usr/bin/env node
//17、正确使用es6语法
//7、正确使用fs模块
const fs = require("fs");
const { program } = require('commander');
const curPath = process.cwd()+"/";
program
    .version('0.0.1')
    .option('-o, --open <fileName>', 'this is open file')
    .parse(process.argv);
const options = program.opts();
const rpstr = `"children":[{"zwf":"占位符"}]`
const obj = `{"dirname":"lib",${rpstr}}`;
var filename = ""
var dirname = ""
var str = ""
// 8、正确使用递归读取子目录
function fileData(url,com,strify,objs) {
    // 12、正确判断-o后面的文件是否在当前目录存在
    let fileUrl = url+"/"+com
    if(fs.existsSync(fileUrl)){
        // 9、正确在控制台输出最终生成的数据格式
        let fileList = fs.readdirSync(fileUrl)
        console.log(fileList);
        fileList.forEach((item,index)=>{
            if(item.split(".")[1]){
                filename += `{"filename":"${item}"},`
            }else{
                dirname += `{"dirname":"${item}",${strify}},`
                // 8、正确使用递归读取子目录
                fileData(fileUrl,item,strify,str)
            } 
        });
        let dirdata = dirname+filename
        str = objs.replace(strify,`"children":[${dirdata}]`); 
        fs.writeFileSync("list.json",str);
        // fileList.forEach((item,index)=>{
        //     if(item.split(".")[1]){
        //         filename += `{"filename":"${item}"}${index==fileList.length-1?"":","}`
        //     }else{
        //         dirname +=  `{"dirname":"${item}","children":[${fileList}]}${index==fileList.length-1?"":","}`
        //         fileData(url+com,item,strify,str)
        //     }
        // })
    }else{
        console.log(222);
    }
}
// 11、正确判断-o参数
fileData(curPath,options.open,rpstr,obj)